#include "stdafx.h"

void send_patch_request(char * table_name, int id, char * field, int value);

extern "C" BOOL PATCH_TelemetryRecord(char * table, int id, char *Field, int Value, bool enableOutput)
{
	BOOL resp = true;

	output.begin(0);
	if (enableOutput)
		output.Enable();
	else
		output.Disable();

	send_patch_request(table, id, Field, Value);

	return resp;
}

//curl -v  -X PATCH -H Content-Type:application/json -H X-ZUMO-APPLICATION:%AppKey%  -d "{\"completed\": true}" %AzureMobileServiceURL%/tables/%MSTable%/%RecordGUID%

/*
** Send an HTTP GET request to the Azure Mobile Service data API
** Want whole table
*/
void send_patch_request(char * table_name, int id, char * field, int value)
{
	// Azure Mobile Service Application Key
	// You can find this key in the 'Manage Keys' menu on the dashboard
	//const char *ams_key = APP_KEY;
	const char *server = AMW_SERVICE;
	char buffer[60];

	//char requestBuffer[REQUESTBUFFERSIZE];
	output.println("\nConnecting...");
	if (client.connect((char *)server, 80)) {
		output.print(F("sending PATCH "));
		output.print(id);
		output.print(" ");
		output.print(field);
		output.print(" ");
		output.println(value);


		output.print(F("PATCH /tables/"));
		client.print(F("PATCH /tables/"));
		output.print(table_name);
		client.print(table_name);
		output.print(F("/"));
		client.print(F("/"));
		output.print(id);
		client.print(id);
		output.println(F(" HTTP/1.1"));
		client.println(F(" HTTP/1.1"));

		// Host header
		//    sprintf(requestBuffer, "Host: %s", server);
		//    output.println(requestBuffer);
		//    client.println(requestBuffer);

		output.print(F("Host: "));
		client.print(F("Host: "));
		output.println(F(AMW_SERVICE));
		client.println(F(AMW_SERVICE));

		// Azure Mobile Services application key
		output.print(F("X-ZUMO-APPLICATION:"));
		client.print(F("X-ZUMO-APPLICATION:"));
		output.println(F(APP_KEY));
		client.println(F(APP_KEY));



		// JSON content type
		output.println(F("Content-Type: application/json"));
		client.println(F("Content-Type: application/json"));

		// POST body


		// Content 
		sprintf(buffer, "{\"%s\":%d}", field, value);

		// Content length
		client.print("Content-Length: ");
		client.println(strlen(buffer));
		output.print("Content-Length: ");
		output.println(strlen(buffer));

		// End of headers
		client.println();
		output.println();

		// Request body
		client.println(buffer);
		output.println(buffer);



		client.SentHTTPMessage();

	}
	else
	{
		output.println(F("connection failed"));
	}
}
